package com.hczx.caxa.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.hczx.caxa.bean.ResultBean;
import com.hczx.caxa.service.LogFileService;
import com.hczx.caxa.service.SignService;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@Api(tags = "二维图纸签名")
@RestController("sign")
@RequestMapping("/sign")
public class SignController {

    private static Logger logger = LoggerFactory.getLogger(SignController.class);

    final SignService signService;
    final LogFileService logFile;

    public SignController(SignService signService, LogFileService logFile) {
        this.signService = signService;
        this.logFile = logFile;
    }

    @RequestMapping(value = "/doSignDrawing", method = RequestMethod.POST)
    public ResultBean doSignDrawing(String number, String signInfo, @RequestPart("pdfFile") MultipartFile pdfFile) {

        ResultBean result = ResultBean.buildSuccessResult();
        StringBuffer loggerBuffer = new StringBuffer();
        logger.info("number:{}", number);
        logger.info("signInfo:{}", signInfo);
        logger.info("pdfFile:{}", pdfFile.getOriginalFilename());
        loggerBuffer.append(logFile.now()).append("----->StartSignDrawing<-----").append("\n");
        loggerBuffer.append(logFile.now()).append("  -->number:").append(number).append("\n");
        loggerBuffer.append(logFile.now()).append("  -->pdfFile:").append(pdfFile.getOriginalFilename()).append("\n");
        loggerBuffer.append(logFile.now()).append("  -->签名信息如下:").append("\n");
        loggerBuffer.append(JSON.toJSONString(JSONArray.parseArray(signInfo), true)).append("\n");

        try {

            String targetPath = signService.doSignDrawing(loggerBuffer, pdfFile, signInfo);
            result.setMsg(targetPath);

        } catch (Exception e) {
            e.printStackTrace();
            result = ResultBean.buildFailureResult(e.getLocalizedMessage());
        } finally {
            logFile.writeLogFile("sign", number, loggerBuffer.toString());
        }

        return result;
    }

}
